<?php
/**
 * 支付宝PC端扫码支付、手机浏览器支付
 * 使用时需修改application/config.php中的alipay数组中的参数
 * User: Sun
 * Date: 2017/12/25
 * Time: 11:08
 */
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Loader;
ini_set('date.timezone','Asia/Shanghai');
header("Access-Control-Allow-Origin: *");
class Alipay extends Controller
{
    /**
     * 支付宝支付
     */
    function recharge(){
        $money = input("money");
        $data["money"] = $money;
        $data["status"] = '1';
        $rechargeId = Db::name("recharge")->insertGetId($data);
        $params = [
            'subject' => '资源下载',
            'out_trade_no' => $rechargeId,
            'total_amount' => $data["money"],
        ];
        $config = config('alipay');
        //同步跳转
        $config['return_url'] = 'http://'.$_SERVER['HTTP_HOST']."/Admin/Alipay/returnurl?myparams=".base64_encode($_SERVER["HTTP_REFERER"]);
        //异步通知地址
        $config['notify_url'] = 'http://'.$_SERVER['HTTP_HOST']."/Admin/Alipay/notifyurl";
        if(isMobile()){
            $result = \Alipay\Wappay::pay($params,$config);
        }else{
            $result = \Alipay\Pagepay::pay($params,$config);
        }
        echo $result;
    }

    /**
     * 支付宝支付 同步跳转地址
     */
    function returnurl(){
        Loader::import('Alipay.pay.service.AlipayTradeService');
        $params=input('get.');
        $config = config('alipay');
        $alipaySevice = new \AlipayTradeService($config);
        $lastUrl = base64_decode($params["myparams"]);
        unset($params["myparams"]);
        $signResult = $alipaySevice->check($params);
        if($signResult){
            $this->redirect($lastUrl);
        }
        exit();
    }

    /**
     * 支付宝支付 异步跳转地址
     */
    function notifyurl(){
        $params=input('post.');
        $result = \Alipay\Notify::check($params);
        if($result) {
            if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //进行订单处理，并传送从支付宝返回的参数；
                $id = $_POST['out_trade_no'];
                Db::name('recharge')->where('id', $id)->update(['status'=>2]);
            }
            //请不要修改或删除
            echo "success";
        }else {
            //验证失败
            echo "fail";
        }
    }
}